<style lang="less" scoped>

.error {
    margin-top: 10px;
    margin-bottom: 10px;
    color: #EA5C5C;
}

@media screen and (min-width: 769px) {
    .addresses {
        .address {
            cursor: pointer;
            &.active {
                .well {
                    border: 1px solid #53C773;
                }
            }
            .delete-btn,
            .set-default-btn {
                a {
                    &,
                    &:active,
                    &:focus,
                    &:hover {
                        cursor: pointer;
                        text-decoration: none;
                        color: #767676;
                    }
                }
            }
            .set-default-btn {
                display: none;
            }
            .well {
                background-color: #FDFDFD;
                box-shadow: none;
                min-height: 135px;
                &:hover {
                    .set-default-btn {
                        display: inherit;
                    }
                }
            }
            .new {
                color: #767676;
                cursor: pointer;
            }
        }
    }
    .address-detail {
        word-wrap: break-word;
        height: 40px;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}

@media screen and (max-width: 768px) {
  .addresses{
    .private-input{
      margin-bottom: 20px;
    }
  }
  .mobile-icon-add{
/*     font-size: 20px;
font-size: 5.333vw; */
    color: #999999;
  }
  .mobile-new-link{
/*     display: flex;
flex-flow: row nowrap;
align-items: center; */
  }
}

</style>

<template>

<div class="addresses" id="addresses">
    <modal v-model="modal.visible" :ok-text="modal.okText" :title="modal.title" @modal-ok-event="addAddress">
        <vue-form :state='formstate' ref="newForm">

            <validate tag="label" class="col-xs-12">
                <label for="contact_name">收货人/联系人</label>
                <input type="text" class="form-control private-input" placeholder="收货人/联系人" v-model="contact_name" required name="contact_name" />

                <field-messages class="" name="contact_name" show="$touched || $submitted">
                    <div class="error" slot="required">请填写联系人</div>
                </field-messages>
            </validate>

            <validate tag="label" class="col-xs-12">
                <label for="contact_name">联系电话</label>
                <input type="text" class="form-control private-input" id="contact_phone" placeholder="联系电话" v-model="cellphone" required name="cellphone" cellphone-validator>

                <field-messages name="cellphone" show="$touched || $submitted">
                    <div class="error" slot="required">请填写手机号</div>
                    <div class="error" slot="cellphone-validator">请填写正确的手机号</div>
                </field-messages>
            </validate>

            <validate tag="label" class="col-xs-12 city-group padding-reset">
                <div class="col-xs-12">选择地址</div>
                <div class="col-sm-3">
                    <select id="province" ref="province" class="city-select form-control private-input" name="province">
                        <option>--省份--</option>
                        <option v-for="(province, index) in allProvinces" :value="province[1]">{{province[0]}}</option>
                    </select>
                </div>

                <div class="col-sm-3">
                    <select id="city" ref="city" class="city-select form-control private-input" name="city">
                        <option>--城市--</option>
                    </select>
                </div>

                <div class="col-sm-3">
                    <select id="region" ref="region" class="city-select form-control private-input" name="region">
                        <option>--区--</option>
                    </select>
                </div>

                <div class="col-sm-3">
                    <select id="street_id" class="city-select form-control private-input" name="street_id" v-model="street_id" required>
                        <option value="">--街道--</option>
                    </select>
                </div>

                <field-messages name="street_id" show="$touched || $submitted">
                    <div class="col-xs-12 error" slot="required">请选择正确的地址</div>
                </field-messages>
            </validate>

            <validate tag="label" class="col-xs-12">
                <label for="detail">详细地址</label>
                <input type="text" class="form-control private-input" id="detail" placeholder="详细地址" v-model="addressDetail" required name="detail">

                <field-messages name="detail" show="$touched || $submitted">
                    <div class="error" slot="required">请填写详细地址</div>
                </field-messages>
            </validate>

        </vue-form>
    </modal>

    <div class="row hidden-xs">
        <div :class="['col-sm-3', 'address', 'address-item', isInitActive(address.id) ? 'active' : '']" :id="address.id" v-for="(address, index) in allAddress" ref="addressItem">
            <div class="well">
                <div class="" v-if="defaultId == address.id">
                    <a class="pull-right">
                        <i class="fa fa-check-circle-o fa-2x private-color"></i>
                    </a>
                </div>
                <div class="set-default-btn pull-right" v-if="defaultId != address.id">
                    <a v-on:click="setDefaultAddress(address.id)">设为默认</a>
                </div>
                <div class="">
                    <h5>{{address.contact_name}}</h5>
                </div>
                <div class="">
                    {{address.cellphone}}
                </div>
                <div class="address-detail">
                    {{address.address}}
                </div>
                <div class="pull-right delete-btn">
                    <a v-on:click="deleteAddress(address.id)">删除</a>
                </div>
            </div>
        </div>
        <div class="col-sm-3 address" v-if="allAddress.length < 5">
            <div class="well text-center new" v-on:click="newAddress">
                <div class="">
                    <h5><i class="fa fa-plus-circle fa-3x"></i></h5>
                </div>
                <div class="">
                    添加新地址
                </div>
            </div>
        </div>
    </div>

    <div class="address_link visible-xs">
      <a class="new mobile-new-link" href="javascript:void(0)" v-if="allAddress.length < 5" @click="newAddress">
        <i class="icon-add mobile-icon-add"></i>
        新建地址
      </a>
      <hr>
      <a class="info" :id="address.id" v-for="(address, index) in allAddress" ref="addressItem">
        <span :class="['icon-success', isInitActive(address.id) ? 'active' : '']"></span>
        <div class="content" v-on:click="setDefaultAddress(address.id)">
          <h1>
            {{address.contact_name}}
            <span>{{address.cellphone}}</span>
          </h1>
          {{address.address}}
        </div>
        <span class="icon-close" v-on:click="deleteAddress(address.id)"></span>
      </a>
    </div>
</div>

</template>

<script>

import Query from '../query'
import Modal from './modal.vue'
import CascadedSelector from './cascadedSelector.vue'
import SuccessDialog from 'success_alert'
import ErrorDialog from 'error_alert'
import VueForm from 'vue-form'

const options = {
    validators: {
        'cellphone-validator': function(value, attrValue, vnode) {
            return /^\d{11}$/.test(value)
        }
    }
}


export default {
    components: {
        'modal': Modal,
        'cascadedSelector': CascadedSelector
    },
    name: "addresses",
    props: {
        pageType: {
            required: true,
            type: String
        }
    },
    data: function data() {
        return {
            formstate: {},
            allAddress: [],
            allProvinces: [],
            defaultId: null,
            modal: {
                title: "添加新的地址",
                content: "",
                visible: false,
                okText: "确认添加"
            },
            contact_name: '',
            cellphone: '',
            addressDetail: '',
            street_id: '',
        }
    },
    created: function() {},
    mounted() {
        this.initData();

        var vm = this
        var selects = $(this.$el).find('select');
        return selects.change(function() {
            var $this, next_selects;
            $this = $(this);
            next_selects = selects.slice(selects.index(this) + 1);
            $("option:gt(0)", next_selects).remove();
            if (next_selects.first()[0] && $this.val() && !$this.val().match(/--.*--/)) {
                return $.get("/china_city/" + ($(this).val()), function(data) {
                    var i, len, option;
                    if (data.data != null) {
                        data = data.data;
                    }
                    for (i = 0, len = data.length; i < len; i++) {
                        option = data[i];
                        next_selects.first()[0].options.add(new Option(option[0], option[1]));
                    }
                    return next_selects.trigger('china_city:load_data_completed');
                });
            }
        });
    },
    updated: function updated() {},
    methods: {
        initData() {
                var _this = this

                Query.get('/dashboard/addresses').then((data) => {
                    _this.allAddress = data.data
                    _this.defaultId = data.default_id
                    _this.setInputValue(_this.defaultId)
                }).catch((error) => {
                    ErrorDialog.show(error)
                })

                Query.get('/dashboard/addresses/all_province').then((data) => {
                    if (data.status === 'ok') {
                        _this.allProvinces = data.data
                    }
                }).catch((error) => {
                    ErrorDialog.show(error)
                })
            },

            newAddress() {
                this.modal.visible = true
            },

            addAddress() {
                if (this.formstate.contact_name.$invalid) this.formstate.contact_name.$touched = true
                if (this.formstate.cellphone.$invalid) this.formstate.cellphone.$touched = true
                if (this.formstate.street_id.$invalid) this.formstate.street_id.$touched = true
                if (this.formstate.detail.$invalid) this.formstate.detail.$touched = true
                if (this.formstate.$invalid) {
                    this.modal.visible = true
                    return
                } else {
                    Query.post('/dashboard/addresses', {
                        address: {
                            contact_name: this.contact_name,
                            cellphone: this.cellphone,
                            street_id: this.street_id,
                            address: this.addressDetail
                        }
                    }).then((data) => {
                        var _this = this
                        if (data.status == 'ok') {
                            _this.allAddress = data.data
                            _this.defaultId = data.default_id
                            if (_this.allAddress.length <= 1) {
                                _this.setInputValue(_this.defaultId)
                            }

                            this.contact_name = ''
                            this.cellphone = ''
                            this.street_id = null
                            this.detail = ''
                            this.$refs.province.options[0].selected = true
                            this.$refs.city.options[0].selected = true
                            this.$refs.region.options[0].selected = true
                            this.formstate.$invalid = false
                            this.formstate.$touched = false
                            this.formstate.contact_name.$invalid = false
                            this.formstate.contact_name.$touched = false
                            this.formstate.cellphone.$invalid = false
                            this.formstate.cellphone.$touched = false
                            this.formstate.street_id.$invalid = false
                            this.formstate.street_id.$touched = false
                            this.formstate.detail.$invalid = false
                            this.formstate.detail.$touched = false
                        } else {
                            SuccessDialog.show(data.data)
                        }
                    }).catch((error) => {
                        ErrorDialog.show(error)
                    })
                }
            },

            deleteAddress(id) {
                const result = confirm('是否删除该地址！')
                var _this = this
                if (result) {
                    Query.delete('/dashboard/addresses/' + id).then((data) => {
                        if (data.status == 'ok') {
                            _this.allAddress = data.data
                            _this.defaultId = data.default_id
                        } else {
                            ErrorDialog.show('删除失败')
                        }
                    })
                }
            },

            setDefaultAddress(id) {
                var _this = this
                Query.put('/dashboard/addresses/' + id + '/set_default_address').then((data) => {
                    if (data.status == 'ok') {
                        _this.allAddress = data.data
                        _this.defaultId = data.default_id
                        SuccessDialog.show('设置成功。')
                    } else {
                        ErrorDialog.show('设置好失败，请重试！')
                    }
                })
            },

            setInputValue(defaultId) {
                if (defaultId) {
                    $('#input_address_id').val(defaultId)
                } else {
                    console.log('----------------地址id初始化失败------------------')
                }
            },

            isInitActive(id) {
                // if (id === this.defaultId && this.pageType === 'orders') {
                if (id === this.defaultId) {
                    return true
                } else {
                    return false
                }
            }
    },
    mixins: [new VueForm(options)],
}

</script>
